#!/bin/bash

scriptPath=$(dirname $0);
expNum=1

if [ -f delay.sqlite ]
then rm delay.sqlite
fi

echo "BEGIN TRANSACTION;" > delay.sql
echo "CREATE TABLE delay (expNum, time, count, num, cdf, discreteTime);" >> delay.sql


for logPath in $(ls -d *)
do 
	if [[ -d $logPath  && -f $logPath/tmp-delay ]]
	then  
		echo $logPath/tmp-delay
		numLines=$(wc -l $logPath/tmp-delay | awk '{print $1;}')
		awk -v numLines=$numLines -v expNum=$expNum '{print "INSERT INTO delay (expNum,time,count,num) VALUES ("expNum", "$1", "$2", "numLines");";}' $logPath/tmp-delay >> delay.sql
		echo $numLines

	   	expNum=$[$expNum+1]
	fi
done

echo "COMMIT;" >> delay.sql

sqlite3 -batch -separator ' ' delay.sqlite < delay.sql



# analysis


sqlite3 -batch -separator ' ' delay.sqlite "update delay set cdf=100*count/num;"
sqlite3 -batch -separator ' ' delay.sqlite "update delay set discreteTime=time where time<10;"
sqlite3 -batch -separator ' ' delay.sqlite "update delay set discreteTime=(time/10)*10 where time >=10 and time <100;"
sqlite3 -batch -separator ' ' delay.sqlite "update delay set discreteTime=(time/100)*100 where time >=100 and time <1000;"
sqlite3 -batch -separator ' ' delay.sqlite "update delay set discreteTime=(time/1000)*1000 where time >=1000 and time <10000;"
sqlite3 -batch -separator ' ' delay.sqlite "update delay set discreteTime=(time/10000)*10000 where time >=10000 and time <100000;"

sqlite3 -batch -separator ' ' delay.sqlite "select min(time), min(cdf), avg(time), avg(cdf), max(time), max(cdf), discreteTime from delay group by discreteTime;" > tmp-cdf-delayVariation

cat $scriptPath/delayVariation-gnuplot.begin > delayVariation.gplot
PLOT="\"tmp-cdf-delayVariation\" using 5:(\$6/100) ls 3  t \"maximum\""
PLOT=$PLOT", \"tmp-cdf-delayVariation\" using 3:(\$4/100) ls 1 t \"average\""
PLOT=$PLOT", \"tmp-cdf-delayVariation\" using 1:(\$2/100) ls 2  t \"minimum\""
echo "plot "$PLOT >> delayVariation.gplot
gnuplot delayVariation.gplot

